package com.example.filetransfer.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;

public class VersionChecker {
    private static final String VERSION_FILE = "version.properties";
    private static final String CURRENT_VERSION = "1.0.0";
    private static final String VERSION_CHECK_URL = "http://localhost:9999/version";
    private static final String CLIENT_DOWNLOAD_URL = "http://localhost:9999/download/client";

    public static boolean checkForUpdates() {
        try {
            // 从服务器获取最新版本信息
            URL url = new URL(VERSION_CHECK_URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()))) {
                    String serverVersion = reader.readLine().trim();
                    return !serverVersion.equals(CURRENT_VERSION);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean downloadNewVersion() {
        try {
            // 下载新版本客户端
            URL url = new URL(CLIENT_DOWNLOAD_URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                String tempDir = System.getProperty("java.io.tmpdir");
                File newClient = new File(tempDir, "FileTransferClient_new.jar");

                try (InputStream in = conn.getInputStream();
                     FileOutputStream out = new FileOutputStream(newClient)) {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = in.read(buffer)) != -1) {
                        out.write(buffer, 0, bytesRead);
                    }
                }

                // 创建启动脚本
                File startupScript = new File(tempDir, "start_new_client.bat");
                try (PrintWriter writer = new PrintWriter(new FileWriter(startupScript))) {
                    writer.println("@echo off");
                    writer.println("timeout /t 2 /nobreak");
                    writer.println("java -jar \"" + newClient.getAbsolutePath() + "\"");
                    writer.println("del \"" + startupScript.getAbsolutePath() + "\"");
                }

                // 启动新版本
                Runtime.getRuntime().exec("cmd /c start " + startupScript.getAbsolutePath());
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
} 